package com.contract.spirit.ui.password

import android.content.Context
import android.content.Intent
import com.contract.commonlib.util.ext.setOnSingleClickListener
import com.blankj.utilcode.util.ThreadUtils
import com.contract.commonlib.base.BaseActivity
import com.contract.commonlib.http.ext.parseState
import com.contract.commonlib.util.ext.gsonToJson
import com.contract.commonlib.util.ext.showToast
import com.contract.spirit.R
import com.contract.spirit.databinding.ActivitySetPasswordBinding
import com.contract.spirit.manage.CommonConfigManager

/**
 * @author: witness
 * created: 2021/9/28
 * desc: 设置资金密码
 */
class SetPasswordActivity : BaseActivity<ActivitySetPasswordBinding, PasswordViewModel>() {
    override fun setContentView(): Int {
        return R.layout.activity_set_password
    }

    override fun initData() {
        mBinding.viewModel = mViewModel
        mBinding.userInfo = CommonConfigManager.userInfoResponse
        mBinding.apply {
            btnSure.setOnSingleClickListener {
                commitPassword()
            }
            tvGetCode.setOnSingleClickListener {
                getCode()
            }
        }
    }

    override fun registerNecessaryObserver() {
        super.registerNecessaryObserver()
        onGetSmsCodeObserve()
        onSetSuccessObserve()
    }

    private fun onGetSmsCodeObserve() {
        mViewModel.emsCodeObservel.observe(this, {
            parseState(it, {
                mBinding.tvGetCode.start()
            })
        })
    }

    private fun onSetSuccessObserve() {
        mViewModel.setPasswordRes.observe(this, {
            parseState(it, {
                if (CommonConfigManager.userInfoResponse.isSetPassword()) {
                    showToast("密码重置成功")
                } else {
                    showToast("密码设置成功")
                    val userInfoResponse = CommonConfigManager.userInfoResponse
                    userInfoResponse.setIsSetPayPwd(1)
                    CommonConfigManager.userinfo = gsonToJson(userInfoResponse)
                }
                ThreadUtils.runOnUiThreadDelayed({ finish() }, 1000)
            })
        })
    }

    private fun commitPassword() {
        if (mViewModel.password.get().toString() != mViewModel.password2.get().toString()) {
            showToast("两次输入的密码不一致")
            mBinding.etPassword2.setShakeAnimation()
            return
        }
        mViewModel.setPassword()
    }

    private fun getCode() {
        mViewModel.getSmsCode()
    }

    companion object {
        fun launch(mContext: Context) {
            mContext.startActivity(Intent(mContext, SetPasswordActivity::class.java))
        }
    }
}
